package com.xinsoft.controller.qua;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinsoft.aop.ano.SysLog;
import com.xinsoft.common.BusinessType;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.MesProcessDTO;
import com.xinsoft.entity.dto.QuaCheckItemParam;
import com.xinsoft.entity.po.MesDocument;
import com.xinsoft.entity.po.QuaCheckItem;
import com.xinsoft.entity.po.QuaDocument;
import com.xinsoft.entity.po.SysFileHis;
import com.xinsoft.service.QuaCheckItemService;
import com.xinsoft.service.QuaDocumentService;
import com.xinsoft.service.SysDocumentNumService;
import com.xinsoft.service.SysFileHisService;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName QuaCheckItemController
 * @Description 检验项控制层
 * @Author Li9527
 * @Date 2023-7-17 15:43:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/qua/checkItem")
@Api(value = "QuaCheckItemController", tags = {"检验项控制层"})
public class QuaCheckItemController {

    @Autowired
    private QuaCheckItemService quaCheckItemService;

    @Autowired
    private QuaDocumentService documentService;

    @Autowired
    private SysFileHisService fileHisService;
    @Autowired
    private SysDocumentNumService sysDocumentNumService;
    /**
     * @Author Li9527
     * @Description 检验项目-新增
     * @Date 2023/5/17 9:57
     * @params   dept
     * @return com.xinsoft.common.Response<?>
     **/
    @SysLog(title = "检验项目-新增", businessType = BusinessType.INSERT)
    @ApiOperation("新增")
    @PostMapping("/add")
    public Response<?> add(@RequestBody QuaCheckItem checkItem) {
        // 参数校验
        ValidatorUtils.validateEntity(checkItem);
        // 默认已审核
        checkItem.setDoAble(Const.AUDIT_STATUS_NORMAL);
        QuaCheckItem oldcheckItem = quaCheckItemService.getOne(new QueryWrapper<QuaCheckItem>().eq("check_item_name",checkItem.getCheckItemName()));
        if(oldcheckItem != null){
            return Response.fail("该检验项目已存在,请不要重复添加");
        }
        sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.CHECK_PROJECT_DOCUMENT);
        quaCheckItemService.save(checkItem);
        if (checkItem.getSysFileHisList().size() > 0) {
            // 质量文档
            this.saveDocumentlList(checkItem);
        }
        return Response.succeed();
    }

    /**
     * @Author Li9527
     * @Description 更新
     * @Date 2023/5/17 9:57
     * @params   dept
     * @return com.xinsoft.common.Response<?>
     **/
    @ApiOperation("更新")
    @SysLog(title = "检验项目-编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public Response<?> edit(@RequestBody QuaCheckItem checkItem) {
        // 参数校验
        QuaCheckItem oldcheckItem = quaCheckItemService.getOne(new QueryWrapper<QuaCheckItem>().eq("check_item_name",checkItem.getCheckItemName()));
        if(oldcheckItem != null && !checkItem.getId().equals(oldcheckItem.getId())){
            return Response.fail("该检验项目已存在,请不要重复添加");
        }
        ValidatorUtils.validateEntity(checkItem);
        if (checkItem.getSysFileHisList().size() > 0) {
            // 质量文档
            documentService.remove(new QueryWrapper<QuaDocument>().eq("qua_id", checkItem.getId()).eq("qua_type",Const.DOCUMENT_QUA_TYPE.CHECK_ITEM));
            this.saveDocumentlList(checkItem);
        }
        return Response.succeed(quaCheckItemService.updateById(checkItem));
    }

    /**
     * @Author Li9527
     * @Description 获取详情
     * @Date 2023/5/17 9:57
     * @params   id
     * @return com.xinsoft.common.Response<?>
     **/
    @ApiOperation("获取详情")
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        QuaCheckItem quaCheckItem = quaCheckItemService.getById(id);
        // 组装文件列表
        List<QuaDocument> mesDocumentList  = documentService.list(new QueryWrapper<QuaDocument>().eq("qua_id", id).eq("qua_type",Const.DOCUMENT_QUA_TYPE.CHECK_ITEM));
        List<Integer> fileIds = new ArrayList<>();
        for (int i = 0; i < mesDocumentList.size(); i++) {
            fileIds.add(mesDocumentList.get(i).getDocumentId());
        }
        if (mesDocumentList.size() > 0) {
            List<SysFileHis> sysFileHis = fileHisService.listByIds(fileIds);
            quaCheckItem.setSysFileHisList(sysFileHis);
        }
        return Response.succeed(quaCheckItem);
    }

    /**
     * @Author Li9527
     * @Description 删除
     * @Date 2023/5/12 9:20
     * @params   ids
     * @return com.xinsoft.common.Response<?>
     **/
    @ApiOperation("删除")
    @SysLog(title = "检验项目-删除", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            QuaCheckItem quacheckItem = quaCheckItemService.getById(ids.get(i));
            if(quacheckItem != null && quacheckItem.getDoAble().equals(Const.AUDIT_STATUS_NORMAL)){
                return Response.fail("存在已启用检验项目，不允许删除");
            }
        }
        quaCheckItemService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * @Author Li9527
     * @Description 检验项目分页
     * @Date 2023/5/18 10:51
     * @params   param
     * @return com.xinsoft.common.Response<?>
     **/
    @PostMapping("/pageList")
    public Response<?> pageList(@Valid @RequestBody QuaCheckItemParam param) {
        return Response.succeed(quaCheckItemService.findPageListByParam(param));
    }

    /**
     * @Author Li9527
     * @Description 批量审核
     * @Date 2023/5/12 9:20
     * @params   ids
     * @return com.xinsoft.common.Response<?>
     **/
    @ApiOperation("检验项目-批量审核")
    @SysLog(title = "检验项目-批量审核", businessType = BusinessType.UPDATE)
    @PostMapping("/auditBatch")
    public Response<?> auditBacth(@RequestBody List<Integer> ids) {
        Integer auditId =  TokenUtil.getUser().getId();
        List<QuaCheckItem> list = quaCheckItemService.list(new QueryWrapper<QuaCheckItem>().in("id",ids));
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setDoAble(Const.AUDIT_STATUS_NORMAL);
        }
        quaCheckItemService.updateBatchById(list);
        return Response.succeed();
    }

    /**
     * @Author Li9527
     * @Description 批量反审核
     * @Date 2023/5/12 9:20
     * @params   ids
     * @return com.xinsoft.common.Response<?>
     **/
    @ApiOperation("检验项目-批量反审核")
    @SysLog(title = "检验项目-批量反审核", businessType = BusinessType.UPDATE)
    @PostMapping("/unAuditBatch")
    public Response<?> unAuditBatch(@RequestBody List<Integer> ids) {
        List<QuaCheckItem> list = quaCheckItemService.list(new QueryWrapper<QuaCheckItem>().in("id",ids));
        Integer auditId =  TokenUtil.getUser().getId();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setDoAble(Const.AUDIT_STATUS_WAIT);
        }
        quaCheckItemService.updateBatchById(list);
        return Response.succeed();
    }

    private void saveDocumentlList(QuaCheckItem quaCheckItem) {
        if (quaCheckItem.getSysFileHisList() != null && quaCheckItem.getSysFileHisList().size() > 0) {
            List<QuaDocument> quaDocumentList = new ArrayList<>();
            for (int i = 0; i < quaCheckItem.getSysFileHisList().size(); i++) {
                QuaDocument quaDocument = new QuaDocument();
                quaDocument.setQuaId(quaCheckItem.getId());
                quaDocument.setQuaType(Const.DOCUMENT_QUA_TYPE.CHECK_ITEM);
                quaDocument.setDocumentId(quaCheckItem.getSysFileHisList().get(i).getId());
                quaDocumentList.add(quaDocument);
            }
            documentService.saveBatch(quaDocumentList);
        }
    }

}
